package br.com.novavendas.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Dao<T> {
	private static Configuration configuration = null;
	private static ServiceRegistry serviceRegistry = null;
	private static SessionFactory sessionFactory = null;
	
	private Class classe;
	
	public Dao(Class classe){
		this.classe = classe;
		if (configuration == null){
			configuration = new Configuration();
			configuration.configure();
		}
		if (serviceRegistry == null){
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		}
        if (sessionFactory == null) {
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }		
	}
	protected T getById(Long id) throws Exception{
		Session session = getSession();
		try{
			return (T) session.get(classe, id);  
		}catch(Exception ex){
			throw ex;			
		}finally{
			session.close();
		}
	}
	
	protected List<T> listagem() throws Exception{
		Session session = getSession();
		try{
			Query query = session.createQuery("From " + classe);
			return query.list();
		}catch(Exception ex){
			throw ex;			
		}finally{
			session.close();
		}		
	}
    protected Session getSession() {
        return sessionFactory.openSession();
    }	
}